package server

import (
	"awesomeTask/application/client"
	"awesomeTask/application/variable"
	"awesomeTask/commom/KeyHelper"
	"awesomeTask/commom/MessageHelper"
	awesomeTask "awesomeTask/config"
	"awesomeTask/system/event"
	"awesomeTask/system/helper"
	"awesomeTask/system/log"
	"fmt"
	"net"
	"strconv"
)

func BindEvent() {
	event.Register(variable.ON_REGISTER_SERVER, func(args ...interface{}) {
		fmt.Println(args, "==================================>")
	})
	event.Register(variable.ON_ASK_CONNECT_SERVER, func(args ...interface{}) {
		data := args[0].(map[string]interface{})
		ipAddress := KeyHelper.TcpUniqueId(data["listenIpAddress"].(string), int(data["listenPort"].(float64)))
		if data["uniqueId"].(string) == awesomeTask.GetConfigByKey("uniqueId").(string) {
			log.GetLogger().Info("无需连接到本机")
			return
		}
		if _, ok := variable.ServerConnections.Load(ipAddress); ok {
			log.GetLogger().Info("连接已经存在无需再次连接")
			return
		}
		log.GetLogger().Info("节点:" + data["ipAddress"].(string) + ":" + strconv.Itoa(int(data["listenPort"].(float64))) + " 邀请加入连接")
		tcpClient := client.CreateNewClient(data["listenIpAddress"].(string), int(data["listenPort"].(float64)))
		tcpClient.OnConnect(func(connection net.Conn) {
			variable.ServerConnections.Store(ipAddress, connection)
		})
		tcpClient.OnClose(func(conn net.Conn) {
			variable.ServerConnections.Delete(ipAddress)
		})
	})
	/**
	当其他节点寻找主节点
	*/
	event.Register(variable.ON_ASK_FOR_MASTER, func(args ...interface{}) {
		if variable.IsMaster {
			params := args[0].(map[string]interface{})
			connection := params["connection"].(net.Conn)
			data := make(map[string]interface{})
			data["masterIp"] = awesomeTask.GetConfigByKeyWithAlias("listenIpAddress")
			data["masterPort"] = awesomeTask.GetConfigByKeyWithAlias("listenPort")
			data["masterUniqueId"] = awesomeTask.GetConfigByKey("uniqueId")
			MessageHelper.SendEvent(variable.ON_RESPONSE_MASTER, data, connection)
			helper.PrintJson(data)
		}
		if client.ServerCon != nil {
			params := args[0].(map[string]interface{})
			connection := params["connection"].(net.Conn)
			uniqueId := client.ServerCon.RemoteAddr().String()
			masterInfo := client.Nodes[uniqueId]
			data := make(map[string]interface{})
			data["masterIp"] = masterInfo.BindIp
			data["masterPort"] = masterInfo.BindPort
			data["masterUniqueId"] = masterInfo.UniqueId
			MessageHelper.SendEvent(variable.ON_RESPONSE_MASTER, data, connection)
			helper.PrintJson(data)
			return
		}
	})

	event.Register(variable.ON_RESPONSE_MASTER, func(args ...interface{}) {
		data := args[0].(map[string]interface{})
		masterUniqueId := data["masterUniqueId"]
		client.ServerConnectionRange(func(key string, connection client.ServerConnection) {
			if connection.UniqueId == masterUniqueId {
				client.ServerCon = connection.Connetion
				fmt.Println("主节点:" + connection.IpAddress + ",uniqueId:" + connection.UniqueId)
			}
		})
	})
}
